/*
	@author: Nicolas Santamaria
	@date  : 16/09/08
	@what  : Socket Server
*/

#include "Network.h"
#include <iostream>

using namespace std;

namespace Network
{

	TCPSocketServer::TCPSocketServer(): m_parser(NULL)
	{

	}

	TCPSocketServer::~TCPSocketServer()
	{}

	void TCPSocketServer::setParser(BasicParser* p_parser)
	{
		m_parser = p_parser;
	}

	void TCPSocketServer::open(unsigned short p_port)
	{
		m_peerAddr.set(p_port);
		//m_acceptor.open(m_peerAddr);
	}

	int TCPSocketServer::receive()
	{	
		char*			buffer  = (char*)malloc(1024);
		int				writer	= 0;
		size_t			max		= 1024;
		ssize_t			n		= 0;
		
		

		do
		{
			n = m_stream.recv_n((void*)(buffer[writer]),1);
			writer += n;
		}
		while( (writer < max) && (n>0));

		switch( n )
		{
		case -1:
		  return -1;
		case 0:
		  return 0;
		default:
			m_parser->handle(buffer, writer);
		}


		return 0;
	}


	ServerThread::ServerThread() : m_stop(false)
	{
		cout << "ServerThread ctor" << endl;
	}

	int ServerThread::svc()
	{
		TCPSocketServer server;

		Parser* parser = new Parser();

		server.setParser(parser);

		server.open(); //default port

		while(!m_stop)
		{

			if (server.receive() == -1)
				cout << "Error on reception" << endl;
		}

		return 0;
	}

	void ServerThread::stop()
	{
		m_stop = true;
	}

	void ServerThread::close()
	{
		stop();
		this->wait();
	}

}